import { mapGetters } from 'vuex'
import { getData, service } from '@vimi/utils-api'
// import { MANAGE_JOBS, MANAGE_SCOPES } from '@/credit/plugins/constant'
import { exportExcel } from '@/credit/mixin/taskTableProvinceUnion'

export default {
  data() {
    return {
      loading: false,
      tableData: [],
      totalCount: 0,
      exportLoading: false,
      useManage: true,
      tableName: 'customer_related',
      dateFmt: 'yyyy-MM-dd hh:mm',
    }
  },
  computed: {
    ...mapGetters(['clientId', 'job', 'userId', 'user']),
    manageParams() {
      // const isScope = MANAGE_SCOPES.some(item => this.user.scopeArr.includes(item))
      // const params = this.useManage && (MANAGE_JOBS.includes(this.job) || isScope) ? {} : {
      //   'orWhere.pre_approval_person.eq': this.userId,
      //   'orWhere.res_a.eq': this.userId,
      //   'orWhere.res_b.eq': this.userId,
      //   'orWhere.res_user_id_risk_point.eq': this.userId
      // }
      // params['service_id.eq'] = this.clientId
      // params['gua_type.eq'] = '4'
      return {
        'service_id.eq': this.clientId,
        'gua_type.eq': 4,
        'channel_type.eq': 0,
      }
    },
  },
  methods: {
    getParams() {
      return {
        ...this.params,
        ...this.manageParams,
      }
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order || {})
      )
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res = {}] = await this.fetchData(this.getParams())
      this.loading = false

      const data = res.data || {}
      this.totalCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.dataAdapter)
    },
    async exportExcel(filename) {
      this.exportLoading = true
      exportExcel({
        filename,
        tableColumns: this.tableColumns,
        params: this.getParams(),
        dataAdapter: this.dataAdapter,
        fetchData: this.fetchData,
        onLoaded: () => {
          this.exportLoading = false
        },
      })
    },
  },
}

const invKeys = [
  'PROJECT_APPROVAL-RESA',
  'PROJECT_APPROVAL-RESB',
  'PROJECT_APPROVAL-RES_MANAGE',
  'PROJECT_APPROVAL-RISK',
  'PROJECT_APPROVAL-RISK_MANAGE',
  'PROJECT_APPROVAL-JURY',
  'PROJECT_APPROVAL-SECRETART',
  'PROJECT_APPROVAL-JURY_DIRECTOR',
  'PROJECT_APPROVAL-RES_MANAGE',
]
const riskKeys = ['RISK_REVIEW_APPROVAL-RES', 'RISK_REVIEW_APPROVAL-RES_MANAGE']

// 正在审批中的任务
export const getInvingPerson = relatedList =>
  relatedList.length
    ? getData({
        table: 'task_list',
        params: {
          'customer_related_id.in': relatedList.map(it => it.customer_related_id).join(','),
          'task_status.eq': 0,
          'wf_node.in': [...invKeys, ...riskKeys].join(','),
          fields: ['customer_related_id', 'task_person', 'wf_node'],
        },
      }).then(res =>
        (res?.data || []).reduce(
          (prev, curr) => {
            const { customer_related_id: relatedId } = curr
            if (riskKeys.includes(curr.wf_node)) {
              ;(prev.risk[relatedId] || (prev.risk[relatedId] = [])).push(curr.task_person)
            } else {
              ;(prev.inv[relatedId] || (prev.inv[relatedId] = [])).push(curr)
            }
            return prev
          },
          { inv: {}, risk: {} }
        )
      )
    : Promise.resolve({ inv: {}, risk: {} })

// 获取省农担审批内容
export const getFollow = (relatedList, key = 'PROJECT_APPROVAL') =>
  relatedList.length
    ? service
        .get(
          `/api/credit/wf/follow/?wfKey=${key}&wfRelatedId=${relatedList
            .map(it => it.customer_related_id)
            .join(',')}`
        )
        .then(res => {
          return res?.data
        })
    : Promise.resolve({})

export const getFollowInfo = (ids, key = 'BH_QUIT_APPROVAL') =>
  ids.length
    ? service.get(`/api/credit/wf/follow/?wfKey=${key}&wfRelatedId=${ids.join(',')}`).then(res => {
        return res?.data
      })
    : Promise.resolve({})

// 审批中的任务
export const getTaskPerson = (relatedList, wf = 'PROJECT_APPROVAL') =>
  relatedList.length
    ? getData({
        table: 'task_list',
        params: {
          'customer_related_id.in': relatedList.map(it => it.customer_related_id).join(','),
          'task_status.eq': 0,
          'workflow_key.eq': wf,
          fields: ['customer_related_id', 'task_person', 'workflow_key'],
        },
      }).then(res =>
        (res?.data || []).reduce((prev, curr) => {
          const { customer_related_id: relatedId } = curr
          prev[relatedId] = prev[relatedId] || []
          prev[relatedId].push(curr.task_person)
          return prev
        }, {})
      )
    : Promise.resolve({})
